package com.cc.crm.web;

import com.cc.crm.entity.SysRight;
import com.cc.crm.entity.SysRole;
import com.cc.crm.service.IRightService;
import com.cc.crm.service.IRoleService;
import com.github.pagehelper.Page;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {
    private Logger log = org.slf4j.LoggerFactory.getLogger(RoleController.class);
    @Autowired
    private IRoleService iRoleService;

    @Autowired
    private IRightService iRightService;

    @RequestMapping("/list")
    public ModelAndView listByPage(@RequestParam(value = "page", defaultValue = "1") int page,
                                   @RequestParam(value = "pageSize", defaultValue = "3") int pageSize) {
        log.debug("进入listByPage......page={},pageSize={}", page, pageSize);
        ModelAndView mv = new ModelAndView();
        Page rolePage = iRoleService.listByPage(page, pageSize);
        mv.addObject("roles", rolePage.getResult());
        mv.addObject("curPage", rolePage.getPageNum());
        mv.addObject("pages", rolePage.getPages());
        mv.addObject("pageSize", rolePage.getPageSize());
        mv.addObject("counts", rolePage.getCountColumn());
        mv.setViewName("~right/role/list");
        return mv;
    }

    @RequestMapping("/dipatch")
    public ModelAndView dipatch(int roleId) {
        ModelAndView mv = new ModelAndView();
        //1，根据id获取当前信息(包括所有的权限信息)
        SysRole curRole = iRoleService.get(roleId);
        //2，获取当前角色的所有权限信息
        List<SysRight> rights = curRole.getCurRights();
        //3，获取当前角色的所有权限权限编码信息

        //4，获取所有权限信息
        List<SysRight> rightList = iRightService.list();
        //5.将当前角色有的权限标记
        for (SysRight rt : rights) {
            for (SysRight r : rightList) {
                if (r.getRightCode().equalsIgnoreCase(rt.getRightCode())) {
                    r.setIsSelected(1);//被选中
                    break;
                }
            }
        }
        mv.addObject("rightList", rightList);
        mv.addObject("curRole", curRole);
        mv.setViewName("~right/role/roleRight");
        return mv;
    }


    @RequestMapping("/updateRight")
    @ResponseBody
    public String updateRight(String[] interest, int roleId) {
        for (int i = 0; i < interest.length; i++) {
            System.out.println(interest[i]);
        }
        System.out.println(roleId);
        //1.先删除该角色的所有权限
        int delResult = iRoleService.deleteRightsWithRole(roleId);
        //2.添加该角色的所有权限到role_right表
        iRoleService.saveRightsWithRole(interest, roleId);
        return "{\"code\":1,\"msg\":\"更新成功！！\"}";
    }
}
